export default {
  // 命名空间
  namespaced: true,
  
  state:() =>({
    cart: JSON.parse(uni.getStorageSync('cart')|| '[]') 
  }),
  mutations:{
    // 加入购物车
    addToCart(state,goods){
      const findResult = state.cart.find((x)=> x.goods_id === goods.goods_id)
      
      if(!findResult){
        state.cart.push(goods)
      }else{
        findResult.goods_count++
      }
      this.commit('m_cart/saveToStorage')
      
    },
    // 持久化处理
    saveToStorage(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    //更新购物车商品选中状态
    updataGoodsState(state,goods){
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult){
        findResult.goods_state = goods.goods_state
        this.commit('m_cart/saveToStorage')
      }
    },
    // 更新商品所有选中状态
    updateAllGoodsState(state,newState){
      state.cart.forEach(x => x.goods_state = newState)
      this.commit('m_cart/saveToStorage')
    },
    //更新购物车商品数量
    updataGoodsCount(state,goods){
      const findResult = state.cart.find(x => x.goods_id === goods.goods_id)
      if(findResult){
        findResult.goods_count = goods.goods_count
        this.commit('m_cart/saveToStorage')
      }
    },
    //滑动删除购物车
    removeGoodsById(state,goods){
      state.cart = state.cart.filter(x => x.goods_id !== goods.goods_id)
      this.commit('m_cart/saveToStorage')
    },
    // 批量删除购物车
    romvgoods(state){
      state.cart = state.cart.filter(x => !x.goods_state)
      this.commit('m_cart/saveToStorage')
    }
    
  },
  
  getters:{
    // 统计购物车商品数量
    total(state){
      let count = 0
      state.cart.forEach(goods => count += goods.goods_count)
      return count
    },
    // 勾选商品数量
    checkedCound(state){
      return state.cart.filter(x => x.goods_state).reduce((total,item)=>total +=item.goods_count,0)
    },
    // 已勾选商品总价
    checkGoodsMaount(state){
      return state.cart.filter(x => x.goods_state).reduce((total,item)=>total +=item.goods_count * item.goods_price,0).toFixed(2)
    }
  },
}